package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneException;
import com.atguigu.gulimall.member.exception.UsernameException;
import com.atguigu.gulimall.member.to.MemberUserRegisterTo;
import com.atguigu.gulimall.member.vo.GiteeSocialUserVo;
import com.atguigu.gulimall.member.vo.MemberUserLoginVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    private MemberLevelDao memberLevelDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberUserRegisterTo user) {
        MemberEntity memberEntity = new MemberEntity();
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        // 设置会员等级
        memberEntity.setLevelId(levelEntity.getId());
        //设置其它的默认信息
        //检查用户名和手机号是否唯一。感知异常，异常机制
        checkPhoneUnique(user.getPhone());
        checkUserNameUnique(user.getUserName());
        memberEntity.setMobile(user.getPhone());
        memberEntity.setUsername(user.getUserName());
        memberEntity.setNickname(user.getUserName());
        //密码进行MD5加密
        // 彩虹表：各种破解md5密码，进行暴力破解，所以要进行加盐处理
        // String s = DigestUtils.md5DigestAsHex(user.getPassword().getBytes()); md5加密，但不能直接进行加密存储，所以要加盐、
        // 加盐，如果知道加的盐值，则可以知道原始密码
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        // encodedPassword 传入，可以判断是否匹配 ,100个用户123456，其加密的盐都不一样，但是都可以进行判断匹配
        bCryptPasswordEncoder.matches(user.getPassword(), "");
        String encode = bCryptPasswordEncoder.encode(user.getPassword());
        memberEntity.setPassword(encode);
        // 默认性别为女
        memberEntity.setGender(0);
        memberEntity.setCreateTime(new Date());

        this.baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneException {
        // 只要数据库中存在记录，那就是不唯一
        Integer phoneCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));

        if (phoneCount > 0) {
            throw new PhoneException();
        }

    }

    @Override
    public void checkUserNameUnique(String userName) throws UsernameException {

        Integer usernameCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));

        if (usernameCount > 0) {
            throw new UsernameException();
        }
    }

    @Override
    public MemberEntity login(MemberUserLoginVo vo) {
        String loginAcct = vo.getLoginacct();
        String password = vo.getPassword();

        //1、去数据库查询 SELECT * FROM ums_member WHERE username = ? OR mobile = ?
        MemberEntity memberEntity = this.baseMapper.selectOne(
                new QueryWrapper<MemberEntity>().eq("username", loginAcct)
                        .or()
                        .eq("mobile", loginAcct)
        );
        if(memberEntity == null){
            // 数据库中没有该注册信息，登录失败
            return null;
        }else{
            // 获取到数据，获取数据库中的password
            String dataPassword = memberEntity.getPassword();
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            // matches() 后跟明文密码、编码后的密码两个参数，明文密码是页面登录获取的密码，数据库中跟的密码是加盐之后的密码
            // 进行密码匹配
            boolean matches = bCryptPasswordEncoder.matches(password, dataPassword);
            if(matches){
                // 登录成功，返回数据库中的用户信息，进行显示
                return memberEntity;
            }
        }

        return null;
    }
    /**
     * Gitee社交登录（登录和注册功能合并）
     */
    @Override
    public MemberEntity login(GiteeSocialUserVo user) {
        // 1.判断当前用户是否已经在本系统注册
        MemberEntity weiboEntity = baseMapper.selectOne(
                new QueryWrapper<MemberEntity>().eq("weibo_uid", user.getId())
        );
        if(weiboEntity != null){
            // 说明已经注册过，直接返回
            MemberEntity memberEntity = new MemberEntity();
            /*根据传入的实体对象中的主键（在这里是 id 属性）来确定要更新的记录。
            如果数据库中存在与传入实体对象具有相同主键的记录，那么这条记录将被更新为新的属性值。*/
            memberEntity.setId(weiboEntity.getId());
            memberEntity.setAccessToken(user.getAccess_token());
            memberEntity.setExpiresIn(user.getExpires_in());
            baseMapper.updateById(memberEntity);
            // 返回
            weiboEntity.setAccessToken(user.getAccess_token());
            weiboEntity.setExpiresIn(user.getExpires_in());
            return weiboEntity;
        }else{
            // 未注册
            MemberEntity memberEntity = new MemberEntity();
            HashMap<String, String> queryMap = new HashMap<>();
            queryMap.put("access_token", user.getAccess_token());
//            queryMap.put("uid", user.getUid());
            try {
                HttpResponse getResponse = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), queryMap);
                if(getResponse.getStatusLine().getStatusCode() == 200){
                    // 查询用户信息成功
                    String json = EntityUtils.toString(getResponse.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    String loginName = jsonObject.getString("login");
                    String avatarUrl = jsonObject.getString("avatar_url");
                    String email = jsonObject.getString("email");
                    String id = jsonObject.getString("id");
                    // 封装注册信息
                    memberEntity.setId((long) Integer.parseInt(id));
                    memberEntity.setNickname(name);
                    memberEntity.setUsername(loginName);
                    memberEntity.setEmail(email);
                    memberEntity.setGender("m".equals(gender) ? 1 : 0);
                    memberEntity.setHeader(avatarUrl);
                    memberEntity.setCreateTime(new Date());
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            // 封装其他信息(未查询到也要)
            memberEntity.setWeiboUid(user.getId());
            memberEntity.setAccessToken(user.getAccess_token());
            memberEntity.setExpiresIn(user.getExpires_in());
            //把用户信息插入到数据库中
            baseMapper.insert(memberEntity);
            return memberEntity;
        }
    }

}